package com.ktgj.hotel.utils;

import okhttp3.*;

import java.io.*;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;

/**
 * 酒店渠道通用网络层
 */
public class NetUtils {
    private OkHttpClient client;

//    private static final byte[] LOCKER = new byte[0];
//    private static NetUtils mInstance;
//    /**
//     * 单例模式获取NetUtils
//     *
//     * @return
//     */
//    public static NetUtils getInstance() {
//        if (mInstance == null) {
//            synchronized (LOCKER) {
//                if (mInstance == null) {
//                    mInstance = new NetUtils();
//                }
//            }
//        }
//        return mInstance;
//    }

    public NetUtils() {
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
        //读取超时
        clientBuilder.readTimeout(6, TimeUnit.SECONDS);
        //连接超时
        clientBuilder.connectTimeout(6, TimeUnit.SECONDS);
        //写入超时
        clientBuilder.writeTimeout(6, TimeUnit.SECONDS);
        clientBuilder.hostnameVerifier((hostname, session) -> true);
        client = clientBuilder.build();
    }

    /**
     * 自定义网络回调接口
     */
    public interface MyNetCall {
        void success(Call call, Response response) throws IOException;

        void failed(Call call, IOException e);
    }

    /**
     * get请求，同步方式，获取网络数据，是在主线程中执行的，需要新起线程，将其放到子线程中执行
     *
     * @param url
     * @return
     * @throws IOException
     */
    public Response get(String url) throws IOException {
        //1 构造Request
        Request.Builder builder = new Request.Builder();
//        builder.addHeader("Content-Encoding", "gzip");
        builder.addHeader("Accept-Encoding", "gzip");
//        builder.header("Accept-Encoding", "gzip");
        Request request = builder.get().url(url).build();
        //2 将Request封装为Call
        Call call = client.newCall(request);
        //3 执行Call，得到response
        return call.execute();
    }
    public Response get_https(String url) throws IOException {
        //1 构造Request
        Request.Builder builder = new Request.Builder();
//        builder.addHeader("Content-Encoding", "gzip");
        builder.addHeader("Accept-Encoding", "gzip");
//        builder.header("Accept-Encoding", "gzip");
        Request request = builder.get().url(url).build();
        //2 将Request封装为Call

        Call call =  OKHttpClientBuilder.buildOKHttpClient().build().newCall(request);
        //3 执行Call，得到response
        return call.execute();
    }


    /**
     * post请求，同步方式
     *
     * @param url
     * @param bodyParams
     * @return
     */
    public Response post(String url, String bodyParams) throws IOException {
        //1构造RequestBody
        RequestBody body = FormBody.create(MediaType.parse("application/json"), bodyParams);
        //2 构造Request
        Request.Builder requestBuilder = new Request.Builder();
        Request request = requestBuilder.post(body).url(url).build();
        //3 将Request封装为Call
        Call call = client.newCall(request);
        //4 执行Call，得到response
        return call.execute();
    }
    /**
     * post请求，同步方式
     *
     * @param url
     * @param bodyParams
     * @return
     */
    public Response post_https(String url, String bodyParams) throws IOException {
        //1构造RequestBody
        RequestBody body = FormBody.create(MediaType.parse("application/json"), bodyParams);
        //2 构造Request
        Request.Builder requestBuilder = new Request.Builder();
        Request request = requestBuilder.post(body).url(url).build();
        //3 将Request封装为Call
        Call call =  OKHttpClientBuilder.buildOKHttpClient().build().newCall(request);
        //4 执行Call，得到response
        return call.execute();
    }

    /**
     * get请求，异步方式，获取网络数据，是在子线程中执行的
     *
     * @param url
     * @param myNetCall
     */
//    public void getAsync(String url, final MyNetCall myNetCall) {
//        Request.Builder builder = new Request.Builder();
//        Request request = builder.get().url(url).build();
//        Call call = client.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                myNetCall.failed(call, e);
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                myNetCall.success(call, response);
//            }
//        });
//
//    }

    /**
     * post请求，异步方式，提交数据，是在子线程中执行的
     *
     * @param
     * @param
     * @param
     */
//    public <T> void postAsync(String url, T bodyParams, final MyNetCall myNetCall) {
//        //1构造RequestBody
//        RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(bodyParams));
//        //2 构造Request
//        Request.Builder requestBuilder = new Request.Builder();
//        Request request = requestBuilder.post(body).url(url).build();
//        //3 将Request封装为Call
//        Call call = client.newCall(request);
//        //4 执行Call
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                myNetCall.failed(call, e);
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                myNetCall.success(call, response);
//
//            }
//        });
//    }

    public static void main(String[] args)
    {
        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        String requestData = "https://api.elong.com/rest?format=json&method=hotel.list&user=ac5faca3b9c843d6a6d841c6f7c68f68&timestamp=1655707196&signature=683925b1692d0b7be4137c1c03a38fc7&data=%7B%22Local%22%3A%22zh_CN%22%2C%22Request%22%3A%7B%22arrivalDate%22%3A%222022-06-20%22%2C%22cityId%22%3A%220101%22%2C%22cityName%22%3A%22%E5%8C%97%E4%BA%AC%22%2C%22departureDate%22%3A%222022-06-21%22%2C%22highRate%22%3A0%2C%22lowRate%22%3A0%2C%22pageIndex%22%3A1%2C%22pageSize%22%3A20%2C%22resultType%22%3A%221%2C2%2C3%2C4%22%7D%2C%22Version%22%3A%221.5%22%7D";
        NetUtils netUtils = new NetUtils();
        try
        {
            Response response = netUtils.get(requestData);
            ResponseBody responseBody = response.body();
            InputStream in = new GZIPInputStream(response.body().byteStream());
            br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line;
            while ((line = br.readLine()) != null)
            {
                result.append(line);
            }
            System.out.println(result);
            br.close();
            in.close();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
